from .data_feed import MarketDataFeed, MarketData
import time
import json
from datetime import datetime

class CrossBorderDataFeed(MarketDataFeed):
    """跨境市场数据feed"""
    def __init__(self, config):
        super().__init__(config)
        self.timezone_mapping = {
            'US': 'America/New_York',
            'HK': 'Asia/Hong_Kong',
            'JP': 'Asia/Tokyo',
            'CN': 'Asia/Shanghai'
        }
        self.exchange_status = {}
        self.currency_rates = {}
        self.data_conversion_cache = {}
        
    def _receive_raw_data(self):
        """接收跨境市场原始数据"""
        try:
            if self.socket:
                topic, raw_data = self.socket.recv_multipart()
                parts = topic.decode('utf-8').split('.')
                if len(parts) < 3:
                    return None
                
                market = parts[0]  # 市场代码: US, HK, JP, CN等
                exchange = parts[1]  # 交易所代码
                symbol = '.'.join(parts[2:])  # 标的代码
                
                data = json.loads(raw_data.decode('utf-8'))
                return {
                    'market': market,
                    'exchange': exchange,
                    'symbol': symbol,
                    'data': data
                }
        except Exception as e:
            print(f"Error receiving cross-border data: {str(e)}")
        return None
    
    def _parse_data(self, raw_data):
        """解析跨境市场数据"""
        market = raw_data['market']
        exchange = raw_data['exchange']
        symbol = raw_data['symbol']
        data = raw_data['data']
        
        # 记录交易所状态
        if 'status' in data:
            self.exchange_status[f"{market}.{exchange}"] = data['status']
        
        # 获取或转换价格
        price = data.get('price', 0)
        converted_price = self._convert_currency(market, price)
        
        # 统一时间戳格式
        timestamp = data.get('timestamp', int(time.time() * 1000))
        if isinstance(timestamp, str):
            # 解析不同格式的时间字符串
            try:
                dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
                timestamp = int(dt.timestamp() * 1000)
            except:
                timestamp = int(time.time() * 1000)
        
        # 构建统一的市场数据对象
        additional_fields = {
            'original_price': price,
            'currency': data.get('currency', 'unknown'),
            'market': market,
            'local_timestamp': data.get('local_timestamp', timestamp),
            'exchange_status': self.exchange_status.get(f"{market}.{exchange}", 'unknown')
        }
        
        # 添加市场特定字段
        if market == 'US' and 'pre_market_price' in data:
            additional_fields['pre_market_price'] = data['pre_market_price']
            additional_fields['after_hours_price'] = data.get('after_hours_price')
        
        return MarketData(
            symbol=f"{market}.{symbol}",  # 添加市场前缀，确保全球唯一性
            price=converted_price,
            volume=data.get('volume', 0),
            timestamp=timestamp,
            exchange=exchange,
            data_type=data.get('data_type', 'tick'),
            additional_fields=additional_fields
        )
    
    def _convert_currency(self, market, price):
        """货币转换"""
        if not price or market not in self.timezone_mapping:
            return price
        
        # 获取目标货币（系统默认货币）
        target_currency = self.config.get('target_currency', 'CNY')
        source_currency = self._get_currency_by_market(market)
        
        # 无需转换的情况
        if source_currency == target_currency:
            return price
        
        # 获取汇率并转换
        rate_key = f"{source_currency}_{target_currency}"
        rate = self.currency_rates.get(rate_key, 1.0)
        
        # 缓存转换结果以提高性能
        cache_key = (market, price, rate)
        if cache_key in self.data_conversion_cache:
            return self.data_conversion_cache[cache_key]
        
        converted_price = price * rate
        self.data_conversion_cache[cache_key] = converted_price
        
        # 限制缓存大小
        if len(self.data_conversion_cache) > 10000:
            # 移除最早的缓存项
            for key in list(self.data_conversion_cache.keys())[:1000]:
                del self.data_conversion_cache[key]
        
        return converted_price
    
    def _get_currency_by_market(self, market):
        """根据市场获取货币类型"""
        currency_map = {
            'US': 'USD',
            'HK': 'HKD',
            'JP': 'JPY',
            'CN': 'CNY',
            'EU': 'EUR',
            'UK': 'GBP'
        }
        return currency_map.get(market, 'CNY')
    
    def update_currency_rates(self, rates):
        """更新汇率数据"""
        self.currency_rates.update(rates)
        # 清除缓存，确保使用最新汇率
        self.data_conversion_cache.clear()
    
    def get_exchange_status(self, market=None, exchange=None):
        """获取交易所状态"""
        if market and exchange:
            return self.exchange_status.get(f"{market}.{exchange}", 'unknown')
        return self.exchange_status